using System;
using System.IO;
using Cysharp.Threading.Tasks;
using UnityEngine;

namespace ExceptionModule
{
    public class LogExceptionHandler : IExceptionHandler
    {
        private StreamWriter _sw;
        private FileStream _fs;

        public LogExceptionHandler()
        {
            CreateFile();
        }

        public async UniTask HandleAsync(string logString, string stackTrace, LogType type)
        {
            var error = $"{logString}\n{stackTrace}";
            await _sw.WriteLineAsync(error);
        }

        public void ApplicationQuit()
        {
            _sw?.Close();
            _fs?.Close();
        }


        void CreateFile()
        {
            var dt = DateTime.Now;
            var filename = $"{dt:yyyy-MM-dd-HH-mm-ss}.log";
            var path = Path.Combine(Application.persistentDataPath, filename);
            if (File.Exists(path))
                _fs = new FileStream(path, FileMode.Append);
            else
                _fs = new FileStream(path, FileMode.CreateNew);
            _sw = new StreamWriter(_fs);
        }
    }
}